<template>
    <div class="container">
        <iSearch>
            <template #Button>
                <a-button type="primary" @click="initList">刷新</a-button>
                <a-button type="primary" danger @click="handleAdd" v-iscan="['auth:menu:add']">添加</a-button>
                <a-button type="primary">全部展开</a-button>
            </template>
        </iSearch>

        <iTable :pagination="false" :columns="columns" :tableData="tableData" :rowExpandable="() => false" rowKey="id" childrenColumnName="children" :loading="loading">
            <template #icon="{ record }">
                <span v-if="record.icon">
                    <component :is="record.icon" />
                </span>
                <span v-else>
                    --
                </span>
            </template>
            <template #title="{ record }">
                {{ _t(`layout.Router.${record.translate_key}`) }}
            </template>
            <template #display="{ record }">
                <a-tooltip placement="top">
                    <template #title>
                        <span>点击切换</span>
                    </template>
                    <a-switch v-model:checked="record.display" unCheckedChildren="隐藏" checkedChildren="显示" :checkedValue="iPb.DbAdminMenuDisplay.DbAdminMenuDisplayDisplay" :unCheckedValue="iPb.DbAdminMenuDisplay.DbAdminMenuDisplayHidden" :disabled="(record.level || 0) == 2"   @click="(value: iPb.DbAdminMenuDisplay) => handleSwitchDisplay(record.id,value)" />
                </a-tooltip>
            </template>
            <template #state="{ record }">
                <a-tooltip placement="top">
                    <template #title>
                        <span>点击切换</span>
                    </template>
                    <a-switch v-model:checked="record.state" unCheckedChildren="禁用" checkedChildren="启用" :checkedValue="iPb.DbAdminMenuState.DbAdminMenuStateEnabled" :unCheckedValue="iPb.DbAdminMenuState.DbAdminMenuStateDisabled"  @click="(value: iPb.DbAdminMenuState) => handleSwitchState(record.id,value)" />
                </a-tooltip>
            </template>
            <template #operate="{ record }">
                <a-flex gap="small" horizontal>
                    <a-button type="link" v-iscan="['auth:menu:add']" @click="handleAdd(record.id, record.level)" v-if="record.level != 2" style="color: #e90">添加下级菜单</a-button>
                    <a-button type="link" v-iscan="['auth:menu:edit','disabled']" @click="handleEdit(record.id)">编辑</a-button>
                    <template v-if="!record.children || record.children.length === 0">
                        <iDelete :auth="['auth:menu:del','disabled']" @delete="handleDelete(record.id)"></iDelete>
                    </template>
                </a-flex>
            </template>
        </iTable>
        
        <a-drawer :title="(formState.id || 0) > 0 ? '编辑菜单': '添加菜单'" rootClassName="full-modal-drawer" width="40%" :open="EditVisible" @close="handleEditClose()" :loading="EditLoading">
            <a-form ref="formStateRef" :model="formState" autocomplete="off" :rules="formStateRule" layout="vertical">
                <a-form-item name="type" label="菜单类型">
                    <a-radio-group v-model:value="formState.type" name="radioGroup">
                        <a-radio v-for="(item,index) in DbAdminMenuType" :value="item.value" :key="index">{{ item.label }}</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item name="title" label="菜单标题">
                    <a-input v-model:value="formState.title" placeholder="请输入菜单标题"></a-input>
                </a-form-item>
                <a-form-item name="translate_key" label="菜单key">
                  <a-input v-model:value="formState.translate_key" :disabled="(formState.id || 0) > 0" placeholder="请输入菜单key"></a-input>
                </a-form-item>
                <a-form-item name="pid" label="上级菜单">
                    <a-tree-select v-model:value="formState.pid" @select="handlePid" show-search placeholder="请选择上级菜单" :tree-default-expand-all="true" :tree-data="EditMenuData" :field-names="{ children: 'children', label: 'title', value: 'id'}"></a-tree-select>
                </a-form-item>
                <a-form-item name="icon" label="Icon" v-if="formState.type != iPb.DbAdminMenuType.DbAdminMenuTypeButton">
                    <a-input v-model:value="formState.icon" placeholder="请输入菜单Icon"></a-input>
                </a-form-item>
                <a-form-item name="route" label="路由地址" v-if="formState.type != iPb.DbAdminMenuType.DbAdminMenuTypeButton">
                    <a-input v-model:value="formState.route" placeholder="请输入路由地址"></a-input>
                </a-form-item>
                <a-form-item name="component" label="组件路径" v-if="formState.type == iPb.DbAdminMenuType.DbAdminMenuTypeMenu">
                    <a-input v-model:value="formState.component" placeholder="请输入组件路径" />
                </a-form-item>
                <a-form-item name="auth" label="权限标识" v-if="formState.type != iPb.DbAdminMenuType.DbAdminMenuTypeDirectory">
                    <a-input v-model:value="formState.auth" placeholder="请输入权限标识" />
                </a-form-item>
                <template v-if="formState.type != iPb.DbAdminMenuType.DbAdminMenuTypeButton">
                    <a-form-item label="显示状态" name="display">
                        <a-select v-model:value="formState.display">
                            <a-select-option v-for="(item,index) in DbAdminMenuDisplay" :key="index" :value="item.value">{{ item.label }}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="菜单状态" name="state">
                        <a-select v-model:value="formState.state">
                            <a-select-option v-for="(item,index) in DbAdminMenuState" :key="index" :value="item.value">{{ item.label }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </template>
                <a-form-item label="接口地址" name="action">
                    <a-textarea style="width: 100%;" v-model:value="formState.action" placeholder="请输入菜单对应的接口地址" />
                </a-form-item>
                <a-form-item label="显示排序" name="Sort">
                    <a-input-number style="width: 100%;" v-model:value="formState.sort" placeholder="请输入菜单排序" />
                </a-form-item>
            </a-form>
            <template #extra>
                <a-space>
                    <a-button @click="handleEditClose()">取消</a-button>
                    <a-button type="primary" @click="handleSubmit()">保存</a-button>
                </a-space>
            </template>
        </a-drawer>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { TableColumnsType } from 'ant-design-vue';
import { FormInstance } from 'ant-design-vue';
import { iPb } from '@/protobuf/interface/index'
import { ListAdminMenu } from '@/api/index'
import { CreateAdminMenu, UpdateAdminMenu, ReadAdminMenu, SwitchStateAdminMenu, SwitchDisplayAdminMenu,DeleteAdminMenu  } from '@/api/admin_menu'
import { DbAdminMenuType,DbAdminMenuDisplay,DbAdminMenuState } from '@/tool/const'
import { Message } from '@/tool/antdv';
import { _t } from '@/assets/lang/index.ts';
import { TableWidth } from '@/tool/enum';

const tableData = ref<Array<iPb.IDbAdminMenu>>([])
const loading = ref<Boolean>(false)
const EditLoading = ref<Boolean>(false)

const formStateRef = ref<FormInstance>()
const formState = ref<iPb.IDbAdminMenu>(iPb.DbAdminMenu.create())
const formStateRule = {
    type: [
        { required: true, message: '请选择菜单类型' }
    ],
    title: [
        { required: true, message: "请输入菜单名称" }
    ],
    translate_key: [
      { required: true, message: "请输入菜单key" }
    ],
    route: [
        { required: true, message: "请输入路由地址" }
    ],
    component: [
        { required: true, message: "请输入组件路径" }
    ],
    auth: [
        { required: true, message: "请输入权限标识" }
    ]
}
const EditVisible = ref<Boolean>(false)
const EditMenuData = ref<Array<iPb.IDbAdminMenu>>([])
    
const handleEdit = (id: number) => {
    formStateRef.value?.resetFields()
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const ReadMenuRequest = iPb.Admin.ReadAdminMenuRequest.create({
        id: id
    })
    ReadAdminMenu(ReadMenuRequest).then((result:iPb.IDbAdminMenu) => {
        formState.value = iPb.DbAdminMenu.create(result)
        EditVisible.value = true
        EditLoading.value = false
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleDelete = (id: number) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    DeleteAdminMenu(iPb.Admin.DeleteAdminMenuRequest.create({
        id: id
    })).then((_result: iPb.IDeleteAdminMenuResponse) => {
        EditLoading.value = false
        Message.success({
            content: "删除成功",
        })
        initList()
    })
}

const handleAdd = (pid?: number, level?: number) => {
    formStateRef.value?.resetFields()
    formState.value = iPb.DbAdminMenu.create({
        pid: pid,
        level: (level || 0) + 1
    })
    EditVisible.value = true
}

const handlePid = (_value: number, node: iPb.DbAdminMenu) => {
    if(node.id > 0) {
        formState.value.level = (node.level || 0) + 1
    }else {
        formState.value.level = 0
    }
}


const handleSwitchDisplay = (id: number, value: iPb.DbAdminMenuDisplay) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const formData = iPb.Admin.SwitchDisplayAdminMenuRequest.create({
        id: id,
        display: value
    })
    SwitchDisplayAdminMenu(formData).then((_result:iPb.Admin.ISwitchDisplayAdminMenuResponse) => {
        EditLoading.value = false
        Message.success({
            content: "切换成功",
        })
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSwitchState = (id: number, value: iPb.DbAdminMenuState) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const formData = iPb.Admin.SwitchStateAdminMenuRequest.create({
        id: id,
        state: value
    })
    SwitchStateAdminMenu(formData).then((_result:iPb.Admin.ISwitchStateAdminMenuResponse) => {
        EditLoading.value = false
        Message.success({
            content: "切换成功",
        })
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSubmit = () => {
    const formData = formState.value
    let validateField: string[] = []
    if(formData.type == iPb.DbAdminMenuType.DbAdminMenuTypeDirectory) {
        validateField = ["type","title","route"]
    }
    if(formData.type == iPb.DbAdminMenuType.DbAdminMenuTypeMenu) {
        validateField = ["type","title","route","component","auth"]
    }
    if(formData.type == iPb.DbAdminMenuType.DbAdminMenuTypeButton) {
        validateField = ["type","title","auth"]
    }
    formStateRef.value?.validate(validateField).then(() => {
        if(EditLoading.value) {
            return
        }
        EditLoading.value = true
        if((formData.id || 0) > 0) {
            UpdateAdminMenu(formData).then((_result:iPb.Admin.IUpdateAdminMenuResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "保存成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }else {
            CreateAdminMenu(formData).then((_result:iPb.Admin.ICreateAdminMenuResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "添加成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }
    })
}

const handleEditClose = () => {
    EditVisible.value = false
}

const initList = () => {
    if(loading.value) {
        return
    }
    loading.value = true
    ListAdminMenu(iPb.Admin.ListAdminMenuRequest.create({
        State: [iPb.DbAdminMenuState.DbAdminMenuStateDisabled,iPb.DbAdminMenuState.DbAdminMenuStateEnabled]
    })).then((result:iPb.Admin.IListAdminMenuResponse) => {
        let R = iPb.Admin.ListAdminMenuResponse.create(result)
        if(R.count > 0) {
            function doCreate(data: iPb.IDbAdminMenu) {
                const c = iPb.DbAdminMenu.create(data)
                if(data.children && data.children.length > 0) {
                    c.children = data.children.map(child => doCreate(child));
                }
                return c
            }
            let menu = R.data.map((item) => doCreate(item))
            let editMenuData = JSON.parse(JSON.stringify(menu))
            tableData.value = menu
            const Main:iPb.IDbAdminMenu = {
                id: 0,
                title: "主菜单",
            }
            EditMenuData.value = [Main].concat(editMenuData)
            loading.value = false
        }else {
            tableData.value = []
            EditMenuData.value = [
                {
                    id: 0,
                    title: "主菜单"
                }
            ]
        }
    }).catch(() => {
        loading.value = false
    })
}

const columns:TableColumnsType = [
    {
        title: "标题",
        dataIndex: "title",
        width: TableWidth.Ordinary,
        ellipsis: true,
    },
    {
        title: "图标",
        dataIndex: "icon",
        width: TableWidth.Ordinary,
    },
    {
        title: "路由",
        dataIndex: "route",
        width: TableWidth.Ordinary,
    },
    {
        title: "权重",
        dataIndex: "sort",
        width: TableWidth.State,
    },
    {
        title: "是否显示",
        dataIndex: "display",
        width: TableWidth.State,
    },
    {
        title: "状态",
        dataIndex: "state",
        width: TableWidth.State,
    },
    {
        title: "操作",
        dataIndex: "operate",
        width: TableWidth.Operate,
    }
]

onMounted(() => {
    initList()
})

</script>